<template>
  <el-dialog :model-value="show" title="分配角色" @close="$emit('hide')">
    <el-select v-model="list" multiple placeholder="Select">
      <el-option
        v-for="item in roles"
        :key="item.value"
        :label="item.label"
        :value="item.value"
      />
    </el-select>
    <template #footer>
      <el-button @click="cancel">取消</el-button>
      <el-button type="primary" @click="submit">确定</el-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { Warning } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { ref, watch } from 'vue';
import { getRoleIdAPI, roleListAllAPI, roleUpdateAPI } from './api';

const emit = defineEmits(['hide']); //清空数据

// 是否显示 Dialog
const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
  id: {
    type: Number,
    default: 0,
  },
});

const list = ref<number[]>([]); //选中项绑定值
const roles = ref<{ value: number; label: string }[]>([]); //要渲染的数据

// 获取所有角色
roleListAllAPI().then((res) => {
  if (res.code === 200) {
    // 将请求的数据处理成对象
    roles.value = res.data.map((item) => ({
      label: item.name, //标签名
      value: item.id,
    }));
  }
});

watch(
  () => props.id,
  () => {
    // 弹出分配角色的下拉请求显示旧的角色数据
    getRoleIdAPI(props.id).then((res) => {
      if (res.code === 200) {
        list.value = res.data.map((item) => item.id);
      }
    });
  }
);

const cancel = () => {
  emit('hide');
};
// 分配角色确认按钮
const submit = () => {
  // 二次确认消息提示框
  ElMessageBox.confirm('此操作将修改当前用户角色, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      // 修改成功关闭提示框并清空
      roleUpdateAPI(props.id, list.value).then((res) => {
        if (res.code === 200) {
          emit('hide', true);
          ElMessage.success('修改成功');
        }
      });
    })
    .catch(() => {});
};
</script>
<style lang="less" scoped></style>
